<template>
  <div class="menu_mange">
    <el-card class="table-container">
      <!-- 查询表单 -->
      <el-form :model="state.queryParam" inline label-width="90px" @submit.prevent="conditionEnter">
        <el-form-item label="客户">
          <el-input v-model="state.queryParam.CustName" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="工作号">
          <el-input v-model="state.queryParam.JobNum" placeholder="请输入工作号" />
        </el-form-item>
        <el-form-item label="合同号">
          <el-input v-model="state.queryParam.ContractNum" placeholder="请输入合同号" />
        </el-form-item>
        <el-form-item label="销售员" prop="SaleName">
          <el-input v-model="state.queryParam.SaleName" placeholder="请输入销售员" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getHandle">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="table-header">

        <div class="toolbar-buttons" style="display: flex;gap: 8px;justify-content: end">
          <el-button type="primary" @click="addHandle()">新增</el-button>
          <div v-if="state.selectedRow">
            <el-button type="primary" @click="handlUpload()">文件上传</el-button>
            <el-button type="primary" @click="handlEedit()">编辑</el-button>
            <el-button type="primary" @click="handlDelete()">删除</el-button>
          </div>
          <el-button type="danger" @click="importHandle()">导入</el-button>
          <el-button plain size="default" @click="handleExport">导出</el-button>
        </div>
      </div>

      <el-table
          :data="state.table.data"
          border
          id="clckexportTab"
          style="width: 100%;height: 600px"
          @selection-change="handleSelectionChange"
          v-loading="state.loading"
          show-summary
          :summary-method="getSummaries"
          row-key="Id"
      >
        <el-table-column type="selection" width="55" fixed />
        <el-table-column
            v-for="col in state.table.columns"
            :key="col.prop"
            :prop="col.prop"
            :label="col.label"
            :width="col.minWidth"
            show-overflow-tooltip
            :fixed="col.fixed"
        >
          <template v-if="col.slotName" #default="scope">
            <slot :name="col.slotName" :scope="scope">
              <template v-if="col.slotName === 'index'">
                <span>{{scope.$index+1}}</span>
              </template>
              <template v-if="col.slotName === 'File'">
                <el-link type="primary" @click="handleEvent(scope.row)">查看文件</el-link>
              </template>
              <template v-if="col.slotName === 'Ddate'">
                <div>{{ parseTime(scope.row.Ddate, '{y}-{m}-{d}') }}</div>
              </template>

              <template v-if="col.slotName === 'TDYSDate'">
                <div>{{ parseTime(scope.row.TDYSDate, '{y}-{m}-{d}') }}</div>
              </template>
              <template v-if="col.slotName === 'JHYSDate'">
                <div>{{ parseTime(scope.row.JHYSDate, '{y}-{m}-{d}') }}</div>
              </template>
              <template v-if="col.slotName === 'DeliveryDate'">
                <div>{{ parseTime(scope.row.DeliveryDate, '{y}-{m}-{d}') }}</div>
              </template>
              <template v-if="col.slotName === 'SaleDeliveryDate'">
                <div>{{ parseTime(scope.row.SaleDeliveryDate, '{y}-{m}-{d}') }}</div>
              </template>
              <template v-if="col.slotName === 'JSYSDate'">
                <div>{{ parseTime(scope.row.JSYSDate, '{y}-{m}-{d}') }}</div>
              </template>
              <template v-if="col.slotName === 'ChangeLastDate'">
                <div>{{ parseTime(scope.row.ChangelastDate, '{y}-{m}-{d}') }}</div>
              </template>
              <template v-if="col.slotName === 'ContractAmount'">
                <div>{{ addSeparator(scope.row.ContractAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'KPAmount'">
                <div>{{ addSeparator(scope.row.KPAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'FHUnKPAmount'">
                <div>{{ addSeparator(scope.row.FHUnKPAmount) }}</div>
              </template>

              <template v-if="col.slotName === 'HKJHAmount'">
                <div>{{ addSeparator(scope.row.HKJHAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'HKAmount'">
                <div>{{ addSeparator(scope.row.HKAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'YSKAmount'">
                <div>{{ addSeparator(scope.row.YSKAmount) }}</div>
              </template>
              <template v-if="col.slotName === 'DQYHKamount'">
                <div>{{ addSeparator(scope.row.DQYHKamount) }}</div>
              </template>
            </slot>
          </template>
          <template v-if="col.children">
            <el-table-column
                v-for="child in col.children"
                :key="child.prop"
                :prop="child.prop"
                :label="child.label"
                :width="child.minWidth"
                show-overflow-tooltip
                :fixed="child.fixed">
              <template v-if="child.slotName" #default="scope">
                <slot :name="child.slotName" :scope="scope">
                  <template v-if="child.slotName === 'HTYDHKSJ'">
                    <div>{{ parseTime(scope.row.HTYDHKSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'DHYDSHJ'">
                    <div>{{ parseTime(scope.row.DHYDSHJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'THKDYSJ'">
                    <div>{{ parseTime(scope.row.THKDYSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'YSKHKSJ'">
                    <div>{{ parseTime(scope.row.YSKHKSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'TDYDHKSJ'">
                    <div>{{ parseTime(scope.row.TDYDHKSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'ZBJYDHKSJ'">
                    <div>{{ parseTime(scope.row.ZBJYDHKSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'ZLKDYSJ'">
                    <div>{{ parseTime(scope.row.ZLKDYSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'YXYDHKSJ'">
                    <div>{{ parseTime(scope.row.YXYDHKSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'JSYDHKSJ'">
                    <div>{{ parseTime(scope.row.JSYDHKSJ, '{y}-{m}-{d}') }}</div>
                  </template>
                  <template v-if="child.slotName === 'DYSJYHKAmount'">
                    <div>{{ addSeparator(scope.row.DYSJYHKAmount) }}</div>
                  </template>
                  <template v-if="child.slotName === 'DHSJHKAmount'">
                    <div>{{ addSeparator(scope.row.DHSJHKAmount) }}</div>
                  </template>
                  <template v-if="child.slotName === 'YSKDYSJHKAmount'">
                    <div>{{ addSeparator(scope.row.YSKDYSJHKAmount) }}</div>
                  </template>

                  <template v-if="child.slotName === 'TDDYSJHKAmount'">
                    <div>{{ addSeparator(scope.row.TDDYSJHKAmount) }}</div>
                  </template>

                  <template v-if="child.slotName === 'ZBJDYSJHKAmount'">
                    <div>{{ addSeparator(scope.row.ZBJDYSJHKAmount) }}</div>
                  </template>

                  <template v-if="child.slotName === 'THKAmount'">
                    <div>{{ addSeparator(scope.row.THKAmount) }}</div>
                  </template>

                  <template v-if="child.slotName === 'ZLKAmount'">
                    <div>{{ addSeparator(scope.row.ZLKAmount) }}</div>
                  </template>

                  <template v-if="child.slotName === 'YXDYSJHKAmount'">
                    <div>{{ addSeparator(scope.row.YXDYSJHKAmount) }}</div>
                  </template>

                  <template v-if="child.slotName === 'JSDYSJHKAmount'">
                    <div>{{ addSeparator(scope.row.JSDYSJHKAmount) }}</div>
                  </template>

                </slot>
              </template>

            </el-table-column>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          style="display: flex;justify-content: end;margin-top: 10px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="state.pagination.currentPage"
          :page-sizes="[10, 20, 30, 40,500,1000,2000]"
          :page-size="state.pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="state.pagination.total">
      </el-pagination>
    </el-card>
    <!-- 保持原有弹窗结构 -->
    <!-- 新增弹窗   -->
    <el-dialog top="10px"
        :title="state.title"
        v-model="state.dialogSelectEnt"
        width="90%"
        :destroy-on-close="true"
        :close-on-click-modal="false"
        @close="handleClose"
    >
      <el-form ref="formRef" :model="state.formData" :rules="state.rules" label-width="160px">
        <!-- 基础信息 -->
            <el-row>
              <el-col :span="8">
                <el-form-item label="工作号" prop="JobNum">
                  <el-input v-model="state.formData.JobNum" placeholder="请输入工作号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同号" prop="ContractNum">
                  <el-input v-model="state.formData.ContractNum" placeholder="请输入合同号" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同名称" prop="ContractName">
                  <el-input v-model="state.formData.ContractName" placeholder="请输入合同名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="销售员" prop="SaleName">
                  <el-input v-model="state.formData.SaleName" placeholder="请输入销售员" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户名称" prop="CustCode">
                  <el-select
                      v-model="state.formData.CustCode"
                      filterable
                      placeholder="请选择客户"
                      @change="changeCustCode"
                      style="width: 100%"
                  >
                    <el-option
                        v-for="item in cubasdoc.data"
                        :key="item.cCusCode"
                        :label="item.CustName"
                        :value="item.cCusCode"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同状态" prop="State">
                  <el-input v-model="state.formData.State" placeholder="请输入合同状态" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同金额(元)" prop="ContractAmount">
                  <el-input-number
                      v-model="state.formData.ContractAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入合同金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="变更合同最后签订金额(元)" prop="ChangedCtAmount">
                  <el-input-number
                      v-model="state.formData.ChangedCtAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入变更后金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同签订日期" prop="Ddate">
                  <el-date-picker
                      v-model="state.formData.Ddate"
                      placeholder="请选择签订日期"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同签订交货日期" prop="DeliveryDate">
                  <el-date-picker
                      v-model="state.formData.DeliveryDate"
                      placeholder="请选择交货日期"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="变更合同最后签订交期" prop="ChangeLastDate">
                  <el-date-picker
                      v-model="state.formData.ChangeLastDate"
                      type="date"
                      placeholder="请选择变更后交货期"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目名称" prop="ProjectName">
                  <el-input v-model="state.formData.ProjectName" placeholder="请输入项目名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="虚拟合同归档日期" prop="VirtuallyHTGDDate">
                  <el-date-picker
                      v-model="state.formData.VirtuallyHTGDDate"
                      type="date"
                      placeholder="请输入虚拟归档日期"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

          <!-- 验收资料 -->
            <el-row>
              <el-col :span="8">
                <el-form-item label="交货验收资料" prop="YSInformation">
                  <el-input v-model="state.formData.YSInformation" placeholder="请输入资料类别（确认收入类别）" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="交货验收资料上传最后时间" prop="JHYSDate">
                  <el-date-picker
                      v-model="state.formData.JHYSDate"
                      placeholder="请选择上传时间"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="通电验收资料" prop="TDYStype">
                  <el-input v-model="state.formData.TDYStype" placeholder="请输入通电验收类别（确认收入类别）" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="通电验收资料上传最后时间" prop="TDYSDate">
                  <el-date-picker
                      v-model="state.formData.TDYSDate"
                      placeholder="请选择上传时间"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="结算资料" prop="JSZLtype">
                  <el-input v-model="state.formData.JSZLtype" placeholder="请输入结算资料类别（确认收入类别）" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="结算资料上传最后时间" prop="JSYSDate">
                  <el-date-picker
                      v-model="state.formData.JSYSDate"
                      placeholder="请选择上传时间"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

          <!-- 发货与开票 -->
            <el-row>
              <el-col :span="8">
                <el-form-item label="已发货金额(元)" prop="FHAmount">
                  <el-input-number
                      v-model="state.formData.FHAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入已发货金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="未发货金额(元)" prop="WFHAmount">
                  <el-input-number
                      v-model="state.formData.WFHAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入未发货金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="开票金额(元)" prop="KPAmount">
                  <el-input-number
                      v-model="state.formData.KPAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入开票金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="税率" prop="Rate">
                  <el-input-number
                      v-model="state.formData.Rate"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入税率"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="发货未开票金额(元)" prop="FHUnKPAmount">
                  <el-input-number
                      v-model="state.formData.FHUnKPAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入发货未开票金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="已发货未开票原因" prop="YFHWKPYY">
                  <el-input v-model="state.formData.YFHWKPYY" placeholder="请输入未开票原因" />
                </el-form-item>
              </el-col>
            </el-row>

          <!-- 回款情况 -->
            <el-row>
<!--              <el-col :span="8">-->
<!--                <el-form-item label="计算到期的合同应收款计划金额(元)" prop="HKJHAmount">-->
<!--                  <el-input-number-->
<!--                      v-model="state.formData.HKJHAmount"-->
<!--                      :precision="2"-->
<!--                      :controls="false"-->
<!--                      placeholder="请输入计算到期的合同应收款计划金额"-->
<!--                      style="width: 100%"-->
<!--                  />-->
<!--                </el-form-item>-->
<!--              </el-col>-->
              <el-col :span="8">
                <el-form-item label="实际回款总额(元)" prop="HKAmount">
                  <el-input-number
                      v-model="state.formData.HKAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入实际回款金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="到期应收款余额(元)" prop="DQYHKamount">
                  <el-input-number
                      v-model="state.formData.DQYHKamount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入到期应收余额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="财务应收款余额(元)" prop="YSKAmount">
                  <el-input-number
                      v-model="state.formData.YSKAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入财务应收余额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="回款比例" prop="HKRatio">
                  <el-input-number
                      v-model="state.formData.HKRatio"
                      :precision="4"
                      :controls="false"
                      placeholder="请输入回款比例（如0.95）"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

          <!-- 合同备注 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="合同情况备注" prop="Remark">
                  <el-input
                      v-model="state.formData.Remark"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入合同相关备注"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          <!-- 资料缺失情况 -->
            <el-row>
              <el-col :span="24">
                <el-form-item label="资料缺失情况" prop="ZLQSQK">
                  <el-input
                      v-model="state.formData.ZLQSQK"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入资料缺失情况"
                  />
                </el-form-item>
              </el-col>
            </el-row>

          <!-- 回款阶段明细 -->
            <el-row>
              <!-- 第一阶段：预付款 -->
              <el-col :span="24"><strong>第一阶段：预付款</strong></el-col>
              <el-col :span="8">
                <el-form-item label="预付款（合同约定比例）" prop="YFKYDBL">
                  <el-input-number
                      v-model="state.formData.YFKYDBL"
                      :precision="4"
                      :controls="false"
                      placeholder="请输入比例"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同约定回款时间" prop="HTYDHKSJ">
                  <el-date-picker
                      v-model="state.formData.HTYDHKSJ"
                      placeholder="请选择回款时间"
                      type="date"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="对应时间应回款金额" prop="DYSJYHKAmount">
                  <el-input-number
                      v-model="state.formData.DYSJYHKAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入应回款金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>

              <!-- 第二阶段：到货款 -->
              <el-col :span="24"><strong>第二阶段：到货款</strong></el-col>
              <el-col :span="8">
                <el-form-item label="到货款（合同约定比例）" prop="DHBLAmount">
                  <el-input-number
                      v-model="state.formData.DHBLAmount"
                      :precision="4"
                      :controls="false"
                      placeholder="请输入比例"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同约定回款时间" prop="DHYDSHJ">
                  <el-date-picker
                      v-model="state.formData.DHYDSHJ"
                      type="date"
                      placeholder="请选择回款时间"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="对应时间应回款金额" prop="DHSJHKAmount">
                  <el-input-number
                      v-model="state.formData.DHSJHKAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>

              <!-- 第三阶段：验收款 -->
              <el-col :span="24"><strong>第三阶段：验收款</strong></el-col>
              <el-col :span="8">
                <el-form-item label="验收款（合同约定比例）" prop="YSKBLAmount">
                  <el-input-number
                      v-model="state.formData.YSKBLAmount"
                      :precision="4"
                      :controls="false"
                      placeholder="请输入比例"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同约定回款时间" prop="YSKHKSJ">
                  <el-date-picker
                      v-model="state.formData.YSKHKSJ"
                      type="date"
                      placeholder="请选择回款时间"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="对应时间应回款金额" prop="YSKDYSJHKAmount">
                  <el-input-number
                      v-model="state.formData.YSKDYSJHKAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>

              <!-- 第三阶段：验收款 -->
              <el-col :span="24"><strong>第四阶段：提货款</strong></el-col>
              <el-col :span="8">
                <el-form-item label="验收款（合同约定比例）" prop="THKBLAmount">
                  <el-input-number
                      v-model="state.formData.THKBLAmount"
                      :precision="4"
                      :controls="false"
                      placeholder="请输入比例"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同约定回款时间" prop="THKDYSJ">
                  <el-date-picker
                      v-model="state.formData.THKDYSJ"
                      type="date"
                      placeholder="请选择回款时间"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="对应时间应回款金额" prop="THKAmount">
                  <el-input-number
                      v-model="state.formData.THKAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>


              <!-- 第四阶段：资料款 -->
              <el-col :span="24"><strong>第五阶段：资料款</strong></el-col>
              <el-col :span="8">
                <el-form-item label="验收款（合同约定比例）" prop="ZLKBLAmount">
                  <el-input-number
                      v-model="state.formData.ZLKBLAmount"
                      :precision="4"
                      :controls="false"
                      placeholder="请输入比例"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同约定回款时间" prop="ZLKDYSJ">
                  <el-date-picker
                      v-model="state.formData.ZLKDYSJ"
                      type="date"
                      placeholder="请选择回款时间"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="对应时间应回款金额" prop="ZLKAmount">
                  <el-input-number
                      v-model="state.formData.ZLKAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <!-- 第五阶段：通电款 -->
              <el-col :span="24"><strong>第六阶段：通电款</strong></el-col>
              <el-col :span="8">
                <el-form-item label="通电款（合同约定比例）" prop="TDYDBL">
                  <el-input-number
                      v-model="state.formData.TDYDBL"
                      :precision="4"
                      :controls="false"
                      placeholder="请输入比例"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同约定回款时间" prop="TDYDHKSJ">
                  <el-date-picker
                      v-model="state.formData.TDYDHKSJ"
                      type="date"
                      placeholder="请选择回款时间"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="对应时间应回款金额" prop="TDDYSJHKAmount">
                  <el-input-number
                      v-model="state.formData.TDDYSJHKAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>

              <!-- 第六阶段：运行款 -->
              <el-col :span="24"><strong>第七阶段：运行款</strong></el-col>
              <el-col :span="8">
                <el-form-item label="验收款（合同约定比例）" prop="YXYDBL">
                  <el-input-number
                      v-model="state.formData.YXYDBL"
                      :precision="4"
                      :controls="false"
                      placeholder="请输入比例"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同约定回款时间" prop="YXYDHKSJ">
                  <el-date-picker
                      v-model="state.formData.YXYDHKSJ"
                      type="date"
                      placeholder="请选择回款时间"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="对应时间应回款金额" prop="YXDYSJHKAmount">
                  <el-input-number
                      v-model="state.formData.YXDYSJHKAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>


              <!-- 第七阶段：结算款 -->
              <el-col :span="24"><strong>第八阶段：结算款</strong></el-col>
              <el-col :span="8">
                <el-form-item label="验收款（合同约定比例）" prop="JSYDBL">
                  <el-input-number
                      v-model="state.formData.JSYDBL"
                      :precision="4"
                      :controls="false"
                      placeholder="请输入比例"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同约定回款时间" prop="JSYDHKSJ">
                  <el-date-picker
                      v-model="state.formData.JSYDHKSJ"
                      type="date"
                      placeholder="请选择回款时间"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="对应时间应回款金额" prop="JSDYSJHKAmount">
                  <el-input-number
                      v-model="state.formData.JSDYSJHKAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>

              <!-- 第八阶段：质保金 -->
              <el-col :span="24"><strong>第九阶段：质保金</strong></el-col>
              <el-col :span="8">
                <el-form-item label="质保金（合同约定比例）" prop="ZBJHTYDBL">
                  <el-input-number
                      v-model="state.formData.ZBJHTYDBL"
                      :precision="4"
                      :controls="false"
                      placeholder="请输入比例"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合同约定回款时间" prop="ZBJYDHKSJ">
                  <el-date-picker
                      v-model="state.formData.ZBJYDHKSJ"
                      type="date"
                      placeholder="请选择回款时间"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="对应时间应回款金额" prop="ZBJDYSJHKAmount">
                  <el-input-number
                      v-model="state.formData.ZBJDYSJHKAmount"
                      :precision="2"
                      :controls="false"
                      placeholder="请输入金额"
                      style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
      </el-form>


      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
        v-loading="state.upload.loading"
        :title="state.upload.title"
        v-model="state.upload.open"
        width="400px"
        append-to-body
        :close-on-click-modal="false"
        :before-close="closeFile"
    >
      <el-upload
          ref="uploadRef111"
          action="#"
          drag
          :auto-upload="false"
          :on-change="onChange"
          :before-remove="beforeRemove"
          :file-list="fileList"
          :before-upload="beforeUpload"
          multiple
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm" :loading="state.upload.loading"
          >确 定</el-button
          >
          <el-button @click="closeFile">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 文件上传对话框 -->
    <el-dialog
        v-loading="state.upload1.loading"
        :title="state.upload1.title"
        v-model="state.upload1.open"
        width="60%"
        append-to-body
        :close-on-click-modal="false"
        :before-close="closeFile"
    >
      <el-tabs type="border-card" v-model="state.selectpane">
        <!-- TDYS 上传区域 -->
        <el-tab-pane name="TDYS" label="通电验收">
          <template #label>
            <span> <span class="type-tag tdys-tag">通电验收文件</span></span>
          </template>
          <div class="upload-container">
            <el-upload
                v-if="!state.upload1.detail"
                :action="baseUrl+uploadFileUrl"
                :multiple="true"
                :file-list="tdysFiles"
                :on-change="(file) => handleFileChange(file, 'TDYS')"
                :on-remove="(file) => handleFileRemove(file, 'TDYS')"
                drag>
              <el-icon class="upload-icon"><upload-filled /></el-icon>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip">支持上传多个文件</div>
              </template>
            </el-upload>

            <div class="file-list" v-if="tdysFiles.length">
              <div v-for="(file, index) in tdysFiles" :key="index" class="file-item">
                <div class="file-info">
                  <el-icon class="file-icon"><document /></el-icon>
                  <div>
                    <div>{{ file.name }}</div>
                    <div style="font-size: 12px; color: #7f8c8d;">{{ file.size  }}</div>
                  </div>
                </div>
                <div class="file-actions">
                  <el-link :href="`${file.FileAdd}`" :underline="false" target="_blank">
                    查看
                  </el-link>
                  <el-icon class="action-btn" v-if="!state.upload1.detail" @click="removeFile(file, 'TDYS')"><delete /></el-icon>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- FHYS 上传区域 -->
        <el-tab-pane name="FHYS">
          <template #label>
            <span> <span class="type-tag fhys-tag">发货验收文件</span></span>
          </template>
          <div class="upload-container">
            <el-upload
                v-if="!state.upload1.detail"
                :action="baseUrl+uploadFileUrl"
                :multiple="true"
                :file-list="fhysFiles"
                :on-change="(file) => handleFileChange(file, 'FHYS')"
                :on-remove="(file) => handleFileRemove(file, 'FHYS')"
                drag>
              <el-icon class="upload-icon"><upload-filled /></el-icon>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip">支持上传多个文件</div>
              </template>
            </el-upload>

            <div class="file-list" v-if="fhysFiles.length">
              <div v-for="(file, index) in fhysFiles" :key="index" class="file-item">
                <div class="file-info">
                  <el-icon class="file-icon"><document /></el-icon>
                  <div>
                    <div>{{ file.name }}</div>
                    <div style="font-size: 12px; color: #7f8c8d;">{{ file.size  }}</div>
                  </div>
                </div>
                <div class="file-actions">

                  <el-link :href="`${file.FileAdd}`" :underline="false" target="_blank">
                    查看
                  </el-link>
                  <el-icon class="action-btn" v-if="!state.upload1.detail" @click="removeFile(file, 'FHYS')"><delete /></el-icon>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- JSYS 上传区域 -->
        <el-tab-pane name="JSYS">
          <template #label>
            <span> <span class="type-tag jsys-tag">结算资料文件</span></span>
          </template>
          <div class="upload-container">
            <el-upload
                v-if="!state.upload1.detail"
                :action="baseUrl+uploadFileUrl"
                :multiple="true"
                :file-list="jsysFiles"
                :on-change="(file) => handleFileChange(file, 'JSYS')"
                :on-remove="(file) => handleFileRemove(file, 'JSYS')"
                drag>
              <el-icon class="upload-icon"><upload-filled /></el-icon>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip">支持上传多个文件</div>
              </template>
            </el-upload>

            <div class="file-list" v-if="jsysFiles.length">
              <div v-for="(file, index) in jsysFiles" :key="index" class="file-item">
                <div class="file-info">
                  <el-icon class="file-icon"><document /></el-icon>
                  <div>
                    <div>{{ file.name }}</div>
                    <div style="font-size: 12px; color: #7f8c8d;">{{ file.size }}</div>
                  </div>
                </div>
                <div class="file-actions">
                  <el-link :href="`${file.FileAdd}`" :underline="false" target="_blank">
                    查看
                  </el-link>
                  <el-icon class="action-btn" v-if="!state.upload1.detail" @click="removeFile(file, 'JSYS')"><delete /></el-icon>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" v-if="!state.upload1.detail" @click="submitFilesForm" :loading="state.upload1.loading"
          >确 定</el-button
          >
          <el-button @click="closeFile">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="tsx">
import {userRole,GetOneData} from "@/api/base"
import {computed, onMounted, reactive, ref, toRefs} from "vue"
import {BeginDataMngAdd, BeginDataMngDel, BeginDataMngUpdate, GetPageData, QcImoprtExcel} from "@/api/contract_entry"
import {cubasdocStore} from "@/stores/modules/cubasdoc";
import {debounce, parseTime,addSeparator} from '@/utils/util'
import FileSaver from "file-saver";
import XLSX from "xlsx";


const tAdaptivePageRef: any = ref(null)

const cubasdoc = cubasdocStore()
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadFileUrl = ref("/api/Base/uploadFile"); // 上传文件服务器地址
//表格配置
const state: any = reactive({
  roleList: [],
  selectpane: "FHYS",
  table: {
    // 接口返回数据
    data: [],
    firstColumn: { type: "radio", fixed: true },
    // 表头数据
    columns: [
      { prop: "LineNum", label: "序号", minWidth: 60, slotName: 'index',fixed: 'left' },
      { prop: "JobNum", label: "工作号", minWidth: 110,fixed: 'left'  },
      { prop: "File", label: "文件", minWidth: 110,slotName: 'File' },
      { prop: "ContractNum", label: "合同号", minWidth: 160 },
      { prop: "ContractName", label: "合同名称", minWidth: 120 },
      { prop: "SaleName", label: "销售员", minWidth: 90},
      { prop: "State", label: "合同状态",minWidth: 110},
      { prop: "Ddate", label: "合同签订日期", minWidth: 120,slotName:'Ddate' },
      { prop: "CustName", label: "客户名称", minWidth: 140},
      { prop: "ProjectName", label: "项目名称", minWidth: 100},
      { prop: "ContractAmount", label: "合同金额(元)", minWidth: 120,slotName: "ContractAmount"},
      { prop: "ChangedCtAmount", label: "变更合同最后签订金额(元)", minWidth: 100},
      { prop: "DeliveryDate", label: "合同签订交货日期", minWidth: 100,slotName:'DeliveryDate' },
      { prop: "ChangelastDate", label: "变更合同最后签订交期", minWidth: 100,slotName: 'ChangeLastDate' },
      { prop: "YSInformation", label: "交货验收资料（确认收入类别）", minWidth: 100, },
      { prop: "JHYSDate", label: "交货验收资料上传最后时间", minWidth: 100,slotName: 'JHYSDate' },
      { prop: "TDYStype", label: "通电验收资料（确认收入类别）", minWidth: 100},
      { prop: "TDYSDate", label: "通电验收资料上传最后时间", minWidth: 100,slotName: 'TDYSDate'  },
      { prop: "ZLQSQK", label: "资料缺失情况", minWidth: 110},
      { prop: "Remark", label: "合同情况备注", minWidth: 100 },
      { prop: "JSZLtype", label: "结算资料（确认收入类别）", minWidth: 100 },
      { prop: "JSYSDate", label: "结算资料上传最后时间", minWidth: 100,slotName: 'JSYSDate' },
      { prop: "FHAmount", label: "已发货金额(元)", minWidth: 90 },
      { prop: "WFHAmount", label: "未发货金额(元)", minWidth: 100 },
      { prop: "KPAmount", label: "开票金额(元)", minWidth: 120, slotName: 'KPAmount' },
      { prop: "Rate", label: "税率", minWidth: 120 },
      { prop: "FHUnKPAmount", label: "发货未开票金额(元)", minWidth: 120, slotName: 'FHUnKPAmount' },
      { prop: "YFHWKPYY", label: "已发货未开票原因", minWidth: 100},
      { prop: "HKJHAmount", label: "计算到期的合同应收款计划金额(元)", minWidth: 120, slotName: 'HKJHAmount'},
      { prop: "HKAmount", label: "实际回款总额(元)", minWidth: 120,slotName: 'HKAmount'},
      { prop: "HKRatio", label: "计算回款比列", minWidth: 100,},
      { prop: "YSKAmount", label: "计算财务应收款余额(元)", minWidth: 110,slotName: 'YSKAmount'},
      { prop: "DQYHKamount", label: "计算到期的合同应收款余额(元)", minWidth: 110,slotName: 'DQYHKamount'},

      { prop: "YFK", label: "第一阶段：预付款", minWidth: 300,children: [
          { prop: "YFKYDBL", label: "合同约定比例", minWidth: 100 },
          { prop: "HTYDHKSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'HTYDHKSJ' },
          { prop: "DYSJYHKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'DYSJYHKAmount' },
        ] },
      { prop: "ZLK", label: "第二阶段：资料款", minWidth: 300,children: [
          { prop: "ZLKBLAmount", label: "合同约定比例", minWidth: 100 },
          { prop: "ZLKDYSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'ZLKDYSJ' },
          { prop: "ZLKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'ZLKAmount' },
        ]
      },

      { prop: "THK", label: "第三阶段：提货款", minWidth: 300,children: [
          { prop: "THKBLAmount", label: "合同约定比例", minWidth: 100 },
          { prop: "THKDYSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'THKDYSJ' },
          { prop: "THKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'THKAmount' },
        ]
      },
      { prop: "DHK", label: "第四阶段：到货款", minWidth: 300,children: [
          { prop: "DHBLAmount", label: "合同约定比例", minWidth: 100 },
          { prop: "DHYDSHJ", label: "合同约定回款时间", minWidth: 100,slotName: 'DHYDSHJ' },
          { prop: "DHSJHKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'DHSJHKAmount' },
        ]
      },
      { prop: "YSK", label: "第五阶段：验收进度款", minWidth: 300,children: [
          { prop: "YSKBLAmount", label: "合同约定比例", minWidth: 100 },
          { prop: "YSKHKSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'YSKHKSJ' },
          { prop: "YSKDYSJHKAmount", label: "对应时间应回款金额", minWidth: 120,slotName: 'YSKDYSJHKAmount' },
        ]
      },

      { prop: "TDK", label: "第六阶段：通电款", minWidth: 300,children: [
          { prop: "TDYDBL", label: "合同约定比例", minWidth: 100 },
          { prop: "TDYDHKSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'TDYDHKSJ' },
          { prop: "TDDYSJHKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'TDDYSJHKAmount' },
        ]
      },

      { prop: "YXK", label: "第七阶段：运行款", minWidth: 300,children: [
          { prop: "YXYDBL", label: "合同约定比例", minWidth: 100 },
          { prop: "YXYDHKSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'YXYDHKSJ' },
          { prop: "YXDYSJHKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'YXDYSJHKAmount' },
        ]
      },

      { prop: "YSK", label: "第八阶段：结算款", minWidth: 300,children: [
          { prop: "JSYDBL", label: "合同约定比例", minWidth: 100 },
          { prop: "JSYDHKSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'JSYDHKSJ' },
          { prop: "JSDYSJHKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'JSDYSJHKAmount' },
        ]
      },

      { prop: "ZBJ", label: "第九阶段：质保金", minWidth: 300,children: [

          { prop: "ZBJHTYDBL", label: "质保金（合同约定比例）", minWidth: 150 },
          { prop: "ZBJYDHKSJ", label: "合同约定回款时间", minWidth: 100,slotName: 'ZBJYDHKSJ' },
          { prop: "ZBJDYSJHKAmount", label: "对应时间应回款金额", minWidth: 130,slotName: 'ZBJDYSJHKAmount' }
        ]
      },
    ],
  },
  loading:false,
  isShowSubBut:true,
  isBg:false,
  title: "新增期初合同录入",
  dialogSelectEnt:false,
  formData:{},
  rules: {
    CustCode: [
      { required: true, message: "请选择客户", trigger: "blur" },
    ],
    ContractNum: [{ required: true, message: '请输入合同号', trigger: 'blur' }],
    JobNum: [{ required: true, message: '请输入工作号', trigger: 'blur' }],
    ContractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
    Ddate: [{ required: true, message: '请选择签订日期', trigger: 'change' }],
    IndustryType: [{ required: true, message: '请选择行业类型', trigger: 'change' }],
    ContractAmount: [
      { required: true, message: '请输入合同金额', trigger: 'blur' },
      { type: 'number', message: '金额必须为数字' }
    ],
    DeliveryDate: [{ required: true, message: '请选择交货日期', trigger: 'change' }],
    KPWay: [{ required: true, message: '请选择开票方式', trigger: 'change' }],
    SaleAmount: [
      { required: true, message: '请输入销售订单金额', trigger: 'blur' },
      { type: 'number', message: '金额必须为数字' }
    ],
    ProduceListInfo: [{ required: true, message: '请选择生产订单日期', trigger: 'change' }],
    YSInformation: [{ required: true, message: '请输入验收资料', trigger: 'blur' }],
    FHListInfo: [{ max: 500, message: '长度不能超过500个字符', trigger: 'blur' }]

  },
  selectedRow:null,
  upload: {
    // 是否显示弹出层
    open: false,
    // 弹出层标题
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: {
      // "Content-type": "multipart/form-data"
    },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/api/Base/ImportExcel',
    loading:false
  },
  upload1: {
    // 是否显示弹出层
    open: false,
    // 弹出层标题
    title: '',
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: {
      // "Content-type": "multipart/form-data"
    },
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + '/api/Base/ImportExcel',
    loading:false,
    detail:false,
  },
  pagination: {
    currentPage: 1, // 当前页
    pageSize: 10, // 每页显示条数
    total: 0, // 总条数
    layout: 'total,sizes,prev, pager, next, jumper', // 分页布局
  },
  queryParam:{
    CustName:undefined,
    JobNum:undefined,
    ContractNum:undefined,
    PageIndex:1,
    PageSize:10
  },
})

//选择项
const cusoptions = ref([])

// 文件列表
const tdysFiles = ref([]);
const fhysFiles = ref([]);
const jsysFiles = ref([]);


// 最终参数获取
const getQueryData = computed(() => {
  const data = toRefs(state.queryParam)
  //转换查询参数 "where": [{"name":"JobNum","value":"229"}] 的形式

  let jobNum = {name: "JobNum", value: data.JobNum?.value}
  let ContractNum = {name: "ContractNum", value: data.ContractNum?.value}
  let CustName = {name: "CustName", value: data.CustName?.value,wheretype:1}
  let SaleName = {name: "SaleName", value: data.SaleName?.value,wheretype:1}

  let where=[]
  if(data.JobNum){
    where.push(jobNum)
  }
  if(data.ContractNum){
    where.push(ContractNum)
  }
  if(data.CustName){
    where.push(CustName)
  }
  if(data.SaleName){
    where.push(SaleName)
  }

  return {
    PageIndex: data.PageIndex?.value,
    PageSize : data.PageSize?.value,
    where
  }
})


// 点击查询按钮
const conditionEnter = (data: any) => {

  state.queryData = data

  getData(1)
}


const formatFileSize = (bytes)=> {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]);
}

// 选择当前页码
const handleSizeChange = val => {
  state.pagination.pageSize = val;
  state.queryParam.PageSize = val;
  getData(val)
}

// 选择当前页码
const handleCurrentChange = val => {
  state.pagination.currentPage = val;
  state.queryParam.PageIndex= val
  getData(val)
}


// 获取数据
const getData = async pageNum => {
  state.loading = true
  let data=await GetPageData(getQueryData.value);

  if (data.Code===200){
    state.table.data = data.Data
    state.pagination.total = data.Total
  }
  state.loading = false
}

onMounted(() => {
  getData(1)
  initRoleList()
})


//过滤单位
const cnvbasdocMethod = (query) => {
  if (query) {
    state.loading = true
    setTimeout(() => {
      state.loading = false

      cusoptions.value = cubasdoc.data.filter((its) => {
        return (its.cCusCode.toLowerCase().includes(query.toLowerCase()) || its.ccusabbname.toLowerCase().includes(query.toLowerCase()))
      })
    }, 200)
  } else {
    cusoptions.value = []
  }
}

const reset = () => {

  state.defaultSelectVal=[]
}

function handleExport(fileName='',idName = "#clckexportTab",xlsxParam={ raw: true }){
  let wb = XLSX.utils.table_to_book(
      document.querySelector(idName),
      xlsxParam
  );
  let wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(
        new Blob([wbout], { type: "application/octet-stream" }),
        `合同汇总表.xlsx`
    );
  } catch (e) {
  }
  return wbout;
}

const initRoleList = async () => {
  let res = await userRole({ VT_ID: '合同台账' })
  state.roleList = res.items
}


const handleClose = () => {
  state.dialogSelectEnt = false
}

const addHandle = () => {
  state.dialogSelectEnt = true
  state.formData = {}
}

const handleEvent = async(row) => {
   let axiosResponse = await GetOneData({ id: row.id });
   state.formData = axiosResponse.Data
  //初始化文件
  if (state.formData.TDYS){
    tdysFiles.value = state.formData.TDYS.map(file => ({
      name: file.FileName,
      path: file.FileAdd,
      uid: file.Id,
      status: 'success'
    }))
  }
  if (state.formData.FHYS){
    fhysFiles.value = state.formData.FHYS.map(file => ({
      name: file.FileName,
      path: file.FileAdd,
      uid: file.Id,
      status: 'success'
    }))
  }
  if (state.formData.JSYS){
    jsysFiles.value = state.formData.JSYS.map(file => ({
      name: file.FileName,
      path: file.FileAdd,
      uid: file.Id,
      status: 'success'
    }))
  }
  state.upload1.detail =true
   state.upload1.open = true

}

const handlUpload = async() => {
   let axiosResponse = await GetOneData({ id: state.selectedRow.Id });
   state.formData = axiosResponse.Data
  //初始化文件
  if (state.formData.TDYS){
    tdysFiles.value = state.formData.TDYS.map(file => ({
      name: file.FileName,
      path: file.FileAdd,
      uid: file.Id,
      status: 'success'
    }))
  }
  if (state.formData.FHYS){
    fhysFiles.value = state.formData.FHYS.map(file => ({
      name: file.FileName,
      path: file.FileAdd,
      uid: file.Id,
      status: 'success'
    }))
  }
  if (state.formData.JSYS){
    jsysFiles.value = state.formData.JSYS.map(file => ({
      name: file.FileName,
      path: file.FileAdd,
      uid: file.Id,
      status: 'success'
    }))
  }
  state.upload1.detail =false
   state.upload1.open = true

}
const handlEedit = () => {
  state.formData={}
  state.title='编辑期初合同录入'
  state.formData =JSON.parse(JSON.stringify(state.selectedRow))
  state.dialogSelectEnt = true
}

const handlDelete = () => {
  // BeginDataMngDel
  ElMessageBox.confirm('确认删除工作号为【'+state.selectedRow.JobNum+'】的合同？请仔细核对数据，删除后无法恢复！', '审核提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(async () => {
        let res = await BeginDataMngDel({ id: state.selectedRow.Id })
        if (res.Code === 'OK') {
          ElNotification.success({
            title: '提示',
            message: '删除成功',
            offset: 200
          })
          await getData(1)
        } else
          ElNotification.error({
            title: '提示',
            message: res.Result,
            offset: 200
          })

        await getData(1)
      })
      .catch(() => {})

}

const submitForm = debounce(
    async () => {
      state.loading = true
      try {
        if(state.formData.Id){
          await BeginDataMngUpdate(state.formData);
        }else {
          await BeginDataMngAdd(state.formData);
        }
      } catch (e) {
        console.log(e);
      } finally {
        state.loading = false
        state.dialogSelectEnt = false
        await getData(1)
      }
    },
    false,
    1000
)

//下拉表格选择数据
const selecUpdateChange = (e) => {
  state.selectedRow = e
  state.formData = e
}



//客户选择
function changeCustCode(e){

  //过滤客户
  let cusoptions = cubasdoc.data.filter((its) => {
    return (its.cCusCode.toLowerCase().includes(e.toLowerCase()))
  })[0]
  if (cusoptions){
    //赋值
    state.formData.CustName = cusoptions.ccusabbname
  }

}

//打开新增窗口
function importHandle() {
  state.upload.open = true
}


const fileList = ref([])
const ACCEPTED_EXTENSIONS = [ 'xls', 'xlsx']


const closeFile = () => {
  fileList.value = []

  tdysFiles.value= []
  fhysFiles.value= []
  jsysFiles.value= []

  //--马光文修改【2025-06-13】--修复用户点击取消或页面关闭按钮后无法关闭的情况
  state.upload.open = false
  state.upload1.open = false


}
/**
 * 文件选择改变时触发
 */
function onChange(file, fileListVal) {
  fileList.value = fileListVal
}


function beforeRemove(file, fileListVal) {
  fileList.value = fileListVal
}


// 文件变更处理
const handleFileChange = (file, type) => {


  if (file.status === 'ready')
    return;
  console.log(file,"文件改变")
  // 生成文件路径（模拟）
  file.path = file.response.Data.FileAdd;

  // 添加到对应文件列表
  if (type === 'TDYS') tdysFiles.value.push(file);
  if (type === 'FHYS') fhysFiles.value.push(file);
  if (type === 'JSYS') jsysFiles.value.push(file);
};

// 文件删除处理
const handleFileRemove = (file, type) => {
  if (type === 'TDYS') {
    tdysFiles.value = tdysFiles.value.filter(f => f.uid !== file.uid);
  }
  if (type === 'FHYS') {
    fhysFiles.value = fhysFiles.value.filter(f => f.uid !== file.uid);
  }
  if (type === 'JSYS') {
    jsysFiles.value = jsysFiles.value.filter(f => f.uid !== file.uid);
  }
};

// 手动移除文件
const removeFile = (file, type) => {
  handleFileRemove(file, type);
};

// 预览文件
const previewFile = (file) => {

};



/**
 * 请求前判断文件是否符合要求
 * 如果符合则添加到上传队列
 */
function beforeUpload(file) {
  const extension = file.name.split('.').pop().toLowerCase()
  if (!ACCEPTED_EXTENSIONS.includes(extension)) {
    ElNotification.error({
      title: '提示',
      message: '仅支持 xls, xlsx格式的文件',
      offset: 200
    })
    return false
  }
  return true
}

/** 提交上传文件 */
async function submitFileForm() {
  if (fileList.value.length === 0) {
    ElNotification.error({
      title: '提示',
      message: '请选择要上传的文件',
      offset: 200
    })
    return
  }

  const file = fileList.value[0].raw
  if (!file) return
  state.upload.loading = true

  try {
    let data= await QcImoprtExcel({file:file})
    console.log(data,"qwfkjfikfi")
    //----马光文修改增加了提示信息
    if(data.Code !== "OK") {
      ElNotification.error({
        title: '提示',
        message: data.Result,
        offset: 200,
      })
      return;
    }else {
      ElNotification.success({
        title: '提示',
        message: data.Result,
        offset: 200,
      })
      state.upload.open = false
      await getData()
      closeFile()
    }
  } catch (error) {
    console.log(error);
    ElNotification.error({
      title: '提示',
      message: "【" + file.name + "】导入错误，请检查文件是否正确！",
      offset: 200,
    })
    // 这里可以添加错误提示
  }finally {
    state.upload.loading = false
  }
}


async function submitFilesForm(){
// 处理TDYS文件
  state.formData.TDYS = tdysFiles.value.map(file => ({
    FileName: file.name,
    FileAdd: file.path,
    ConSubId:state.formData.id
  }));

  // 处理FHYS文件
  state.formData.FHYS = fhysFiles.value.map(file => ({
    FileName: file.name,
    FileAdd: file.path,
    ConSubId:state.formData.id
  }));

  // 处理JSYS文件
  state.formData.JSYS = jsysFiles.value.map(file => ({
    FileName: file.name,
    FileAdd: file.path,
    ConSubId:state.formData.id
  }));

  console.log(state.formData,"提交文件")

  let res = await BeginDataMngUpdate(state.formData);
  if(res.Code!=null&&res.Code=="Error")
    {
      ElNotification.error({
        title: '提示',
        message: res.Result,
        offset: 200,
      })
      return;
    }
    else{
      ElNotification.success({
        title: '提示',
        message: '保存成功',
        offset: 200,
      })
      state.upload1.open = false
      closeFile()
    }
}


// 选择当前页码
const sizeChange = val => {

  state.table.pageSize = val
  getData(1)
}

const handleSelectionChange = (val: any[]) => {
  state.selectedRow = val.length === 1 ? val[0] : null
}


const resetHandle = () => {
  state.queryParam = {
    ContractNum: undefined,
    CustName: undefined,
    JobNum: undefined,
    PageIndex:1,
    PageSize:10
  }
  getData(1)
}
const getHandle = () => {
  state.queryParam = {
    ...state.queryParam,
    PageIndex:1
  }
  getData(1)
}

const getSummaries = param => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    if (![11,12,23, 24, 25,26, 28, 29,31,32,35,38,41,44,47].includes(index)) {
      sums[index] = ''
      return
    }

    const values = data.map(item => Number(item[column.property]))
    if (!values.every(value => isNaN(value))) {
      sums[index] = addSeparator(values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0))
      sums[index] += ''
    } else {
      sums[index] = 'N/A'
    }
  })

  return sums
}


</script>

<style scoped lang="scss">

.el-form-item {
  --font-size: 12px;
  --el-form-label-font-size: var(--font-size);
  margin-bottom: 2px!important;
}

h1 {
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 2.5rem;
}

.subtitle {
  color: #7f8c8d;
  font-size: 1.2rem;
  margin-bottom: 30px;
}

.card-container {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
}

.card {
  flex: 1;
  background: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  padding: 20px;
  transition: transform 0.3s ease;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.card h3 {
  color: #3498db;
  border-bottom: 2px solid #f0f5ff;
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.upload-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 20px;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  background: #fafafa;
  transition: all 0.3s;
  cursor: pointer;
}

.upload-area:hover {
  border-color: #3498db;
  background: #f0f9ff;
}

.upload-icon {
  font-size: 48px;
  color: #3498db;
  margin-bottom: 15px;
}

.file-list {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  background: #f8fafc;
  border-radius: 6px;
  margin-bottom: 10px;
  transition: all 0.2s;
}

.file-item:hover {
  background: #e8f4ff;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.file-icon {
  color: #3498db;
  font-size: 20px;
}

.file-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  cursor: pointer;
  color: #7f8c8d;
  transition: color 0.2s;
}

.action-btn:hover {
  color: #3498db;
}

.preview-container {
  margin-top: 30px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
}

.preview-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.json-code {
  background: #2c3e50;
  color: #ecf0f1;
  padding: 15px;
  border-radius: 6px;
  max-height: 300px;
  overflow: auto;
  font-family: 'Courier New', monospace;
  white-space: pre-wrap;
}

.buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.upload-btn {
  padding: 12px 30px;
  font-size: 1.1rem;
}

.type-tag {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 4px;
  font-weight: bold;
  margin-left: 10px;
}

.tdys-tag { background: #e1f0fa; color: #2980b9; }
.fhys-tag { background: #fae6e6; color: #c0392b; }
.jsys-tag { background: #e6f7e6; color: #27ae60; }
</style>


